package com.ipzoe.web.token;

import cn.hutool.core.util.StrUtil;
import com.ipzoe.web.core.consts.Constant;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * 获取token的封装
 */
public class TokenUtil {

    /**
     * 获取token的两种方法
     *
     */
    public static String getToken(HttpServletRequest request) {

        String authToken = null;

        //权限校验的头部
        String tokenHeader = Constant.TOKEN_HEADER_NAME;
        authToken = request.getHeader(tokenHeader);

        //header中没有的话去cookie拿值，以header为准
        if (StrUtil.isEmpty(authToken)) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (tokenHeader.equals(cookie.getName())) {
                        authToken = cookie.getValue();
                    }
                }
            }
        }

        return authToken;
    }
}
